import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {
    FooterToolbar, ModalForm,
    PageContainer, ProFormDigit, ProFormRadio, ProFormSelect, ProFormText,
    ProTable,
    ProFormDateTimePicker,
} from '@ant-design/pro-components';
import {Button, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import type {OrganizationOrderListItem} from './data';
import {organizationOrderList, organizationOrderStartBilling} from './service';
import {ResourceTypeEnum} from "@/pages/order/data.enum";
import {OrderStatusEnum} from "@/pages/data.enum";
import {organizationSelectList} from "@/pages/organization/org-list/service";
/**
 * 添加节点
 *
 * @param fields
 */
const handleSetStartBillingTime = async (StartBillingRequest) => {
    const hide = message.loading('正在设置');
    try {
        let res = await organizationOrderStartBilling({
            ...StartBillingRequest
        });
        if (res?.success != true) {
            throw new Error(res.errorMessage);
        }
        hide();
        message.success('设置成功');
        return true;
    } catch (error) {
        hide();
        message.error('设置失败请重试！');
        return false;
    }
};

/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<OrganizationOrderListItem>;

const OrganizationOrderList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<OrganizationOrderListItem>();
    const [startBillingModalVisible, handleStartBillingModalVisible] = useState<boolean>(false);

    /** 国际化配置 */
    const columns: ProColumns<OrganizationOrderListItem>[] = [
        {
            title: '订单ID',
            dataIndex: 'orderId',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            search: true,
            ellipsis: true, // 关闭自动换行
            valueType: 'select',
            valueEnum: OrderStatusEnum,
        },
        {
            title: '租户',
            dataIndex: "organizationId",
            valueType: 'select',
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await organizationSelectList({includeSystem:false});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.organizationId,
                    })) || []
                );
            },
        },
        {
            title: '租户名称',
            dataIndex: 'organizationName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源类型',
            dataIndex: 'resourceType',
            search: true,
            hidden: true,
            valueType: 'select',
            valueEnum: ResourceTypeEnum,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源ID',
            dataIndex: 'resourceId',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源类型',
            dataIndex: 'resourceTypeName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '资源信息',
            dataIndex: 'resourceDesc',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '结算周期',
            dataIndex: 'billingCycle',
            search: false,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                if (record.billingCycle == 'hour') {
                    return <span>￥{record.unitPrice}/小时</span>;
                } else if (record.billingCycle == 'day') {
                    return <span>￥{record.unitPrice}/天</span>;
                } else if (record.billingCycle == 'month') {
                    return <span>￥{record.unitPrice}/月</span>;
                }
                return record.billingCycle
            },
        },
        {
            title: '开始计费时间',
            dataIndex: 'start',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '最后计费周期',
            dataIndex: 'lastBillingTimeString',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '订单创建时间',
            dataIndex: 'createdAt',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true,
            render: (_, record) => {
                if (record.status == 2) {
                    return [
                        <a
                            key="config"
                            onClick={() => {
                                setCurrentRow(record);
                                handleStartBillingModalVisible(true);
                            }}
                        >
                            开始计费
                        </a>,
                    ]
                }
                return
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<OrganizationOrderListItem, API.ListPagination>
                headerTitle="订单列表"
                actionRef={actionRef}
                rowKey="orderId"
                search={{
                    labelWidth: 90,
                }}
                scroll={{x: true}}
                toolBarRender={() => [
                ]}
                request={organizationOrderList}
                columns={columns}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
            />
            <ModalForm
                title="设置计费"
                width="650px"
                open={startBillingModalVisible}
                onVisibleChange={handleStartBillingModalVisible}
                onFinish={async (value) => {
                    const success = await handleSetStartBillingTime(value as OrganizationOrderListItem);
                    if (success) {
                        handleStartBillingModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    organizationName: currentRow?.organizationName,
                    resourceType: currentRow?.resourceType,
                    resourceDesc: currentRow?.resourceDesc,
                    orderId: currentRow?.orderId,
                }}
            >
                <ProFormText
                    name="orderId"
                    label="订单ID"
                    disabled={true}
                    hidden={true}
                />

                <ProFormText
                    name="organizationName"
                    label="租户"
                    disabled={true}
                />

                <ProFormSelect
                    name="resourceType"
                    label="资源类型"
                    disabled={true}
                    valueEnum={ResourceTypeEnum}
                />

                <ProFormText
                    name="resourceDesc"
                    label="资源详情"
                    disabled={true}
                />

                <ProFormRadio.Group
                    name="billingCycle"
                    label="计费周期"
                    rules={[
                        {
                            required: true,
                            message: '请选择计费周期',
                        },
                    ]}
                    options={[
                        {
                            label: '每小时',
                            value: 'hour',
                        },
                        {
                            label: '每天',
                            value: 'day',
                        },
                        {
                            label: '每月',
                            value: 'month',
                        },
                    ]}
                />
                <ProFormDigit
                    label="单价"
                    name="unitPriceNumber"
                    rules={[
                        {
                            required: true,
                            message: '请输入单价',
                        },
                    ]}
                    width={200}
                    fieldProps={{addonAfter: "元"}}
                    placeholder="请输入单价"
                />
                <ProFormDateTimePicker
                    label="开始计费时间（可选）"
                    width="md"
                    name="start"
                    placeholder={'开始日期'}
                    rules={[
                        {
                            required: true,
                            message: '请选择开始计费时间',
                        },
                    ]}
                />
            </ModalForm>
        </PageContainer>
    );
};

export default OrganizationOrderList;
